package com.example.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.Utils.HttpHelper;
import com.example.training.R;

import java.util.ArrayList;
import java.util.HashMap;

public class OnlineDiskResultsActivity extends Activity implements AbsListView.OnScrollListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.onlinediskresults_activity);

        _filter = getIntent().getStringExtra("filter");
        _site = getIntent().getStringExtra("site");
        _lstOnlineDiskResults = (ListView) findViewById(R.id.lst_onlinediskresults);
        _lstOnlineDiskResults.setOnScrollListener(this);
        _location = 0;
        LoadResults(false);
    }


    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        if (_lastItem >= _adapter.getCount() && scrollState == SCROLL_STATE_IDLE) {
            LoadResults(true);
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        _lastItem = firstVisibleItem + visibleItemCount;
    }

    private void LoadResults(boolean append){
        if(_isLoading)
            return;
        _isLoading=true;
        _pd = ProgressDialog.show(this, "加载数据", "数据加载中...");
        if(append){
            new Thread(){
                public void run(){
                    DoLoadResults(true);
                    _handler.sendEmptyMessage(1);
                }
            }.start();
        } else {
            new Thread(){
                public void run(){
                    DoLoadResults(false);
                    _handler.sendEmptyMessage(0);
                }
            }.start();
        }
    }

    private void DoLoadResults(boolean append){
        final String BAIDU_SESRCH_URL ="http://www.baidu.com/s";
        final String BAIDU_SESRCH_PARAM ="wd=site%%3A%%28%s%%29%%20%s&pn=%d&tn=baiduadv";
        final String GOOLGLESESRCHSTRING ="http://74.125.128.147/custom?hl=zh-CN&sitesearch=%s&q=%s";

        if(append){
            _location += 10;
            String htmlString = HttpHelper.GET(BAIDU_SESRCH_URL, "", "utf-8",
                    String.format(BAIDU_SESRCH_PARAM, _site, _filter, _location));
            _results.addAll(formatHtml(htmlString));

        }else{
            _location = 0;
            String htmlString = HttpHelper.GET(BAIDU_SESRCH_URL, "", "utf-8",
                    String.format(BAIDU_SESRCH_PARAM, _site, _filter, _location));
            _results = formatHtml(htmlString);
            _adapter = new SimpleAdapter(this,
                    _results,
                    R.layout.onlinediskresults_itemstyle,
                    new String[] {"ItemTitle", "ItemUrl"},
                    new int[] {R.id.text_onlinedisk_title,R.id.text_onlinedisk_url});

        }
    }

    private  ArrayList<HashMap<String, Object>> formatHtml(String html){
        final String TITLE_FLAG = "data-tools='{\"title\":\"";
        final String URL_FLAG = "\",\"url\":\"";
        final String END_FLAG = "\"}'>";
        ArrayList<HashMap<String, Object>> results = new ArrayList<HashMap<String, Object>>();

        int pos;
        while (true){
            pos = html.indexOf(TITLE_FLAG);
            if(pos == -1){
                break;
            }
            html = html.substring(pos);
            pos = html.indexOf(URL_FLAG);
            if(pos == -1){
                break;
            }
            String title = html.substring(TITLE_FLAG.length(), pos);
            html = html.substring(pos);
            pos = html.indexOf(END_FLAG);
            if(pos == -1){
                break;
            }
            String url = html.substring(URL_FLAG.length(), pos);

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemTitle", title);
            map.put("ItemUrl", url);
            results.add(map);
        };
        return results;
    }

    private String _filter;
    private boolean _isLoading = false;
    private String _site;
    private ListView _lstOnlineDiskResults;
    private int _location;
    private int _lastItem;
    private SimpleAdapter _adapter;
    ArrayList<HashMap<String, Object>> _results;

    private ProgressDialog _pd;
    private Handler _handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(msg.what == 0){
                _lstOnlineDiskResults.setAdapter(_adapter);
            }
            else if(msg.what == 1){
                _adapter.notifyDataSetChanged();
            }
            _pd.dismiss();
            _isLoading = false;
        }
    };
}
